package com.helin.helinhealth.controller;

import com.helin.helinhealth.common.Result;
import com.helin.helinhealth.dto.ExportRequest;
import com.helin.helinhealth.dto.ExportResponse;
import com.helin.helinhealth.entity.ExportTask;
import com.helin.helinhealth.service.ExportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据导出控制器
 */
@Slf4j
@Tag(name = "数据导出", description = "数据导出相关接口")
@RestController
@RequestMapping("/api/export")
public class ExportController {

    @Autowired
    private ExportService exportService;

    @Operation(summary = "创建导出任务", description = "创建一个数据导出任务")
    @PostMapping("/create")
    public Result<ExportResponse> createExportTask(@RequestBody ExportRequest request) {
        log.info("创建导出任务: {}", request);
        ExportResponse response = exportService.createExportTask(request);
        return Result.success("创建导出任务成功", response);
    }

    @Operation(summary = "查询任务状态", description = "根据任务ID查询导出任务状态")
    @GetMapping("/status/{taskId}")
    public Result<ExportTask> getExportTaskStatus(
            @Parameter(description = "任务ID") 
            @PathVariable Long taskId) {
        log.info("查询导出任务状态: {}", taskId);
        ExportTask task = exportService.getExportTaskStatus(taskId);
        return task != null ? Result.success("获取任务状态成功", task) : Result.error("任务不存在");
    }

    @Operation(summary = "获取下载链接", description = "获取已完成导出任务的文件下载链接")
    @GetMapping("/download-url/{taskId}")
    public Result<String> getDownloadUrl(
            @Parameter(description = "任务ID") 
            @PathVariable Long taskId) {
        log.info("获取导出文件下载链接: {}", taskId);
        String downloadUrl = exportService.getDownloadUrl(taskId);
        return downloadUrl != null ? Result.success("获取下载链接成功", downloadUrl) : Result.error("任务不存在或未完成");
    }
    
    @Operation(summary = "下载导出文件", description = "下载已完成的导出文件")
    @GetMapping("/download/{taskId}")
    public ResponseEntity<byte[]> downloadFile(
            @Parameter(description = "任务ID") 
            @PathVariable Long taskId) {
        log.info("下载导出文件: {}", taskId);
        
        try {
            // 直接调用ExportService的downloadFile方法
            return exportService.downloadFile(taskId);
        } catch (Exception e) {
            log.error("文件下载失败: {}", e.getMessage(), e);
            // 由于返回类型是ResponseEntity<byte[]>，无法直接返回错误信息
            // 这里将抛出异常，由全局异常处理器处理
            throw new RuntimeException("文件下载失败: " + e.getMessage(), e);
        }
    }

    @Operation(summary = "清理过期导出文件", description = "清理过期的导出文件和相关缓存")
    @DeleteMapping("/cleanup")
    public Result<Map<String, Object>> cleanupExportFiles(
            @Parameter(description = "保留天数（可选，默认使用系统配置）") 
            @RequestParam(required = false) Integer days) {
        log.info("清理过期导出文件: 保留天数={}", days);
        
        int deletedCount = exportService.cleanupExportFiles(days);
        Map<String, Object> data = new HashMap<>();
        data.put("deletedFiles", deletedCount);
        
        return Result.success("清理成功", data);
    }
    
    @Operation(summary = "清理导出任务缓存", description = "清理导出任务的内存缓存")
    @DeleteMapping("/clear-cache")
    public Result<Map<String, Object>> clearCache() {
        log.info("清理导出任务缓存");
        
        int clearedCount = exportService.clearCache();
        Map<String, Object> data = new HashMap<>();
        data.put("clearedEntries", clearedCount);
        
        return Result.success("缓存清理成功", data);
    }
} 